package work.comeback.omo.controller.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import work.comeback.omo.model.http.RequestParams;

import java.io.IOException;

@WebFilter(
        filterName = "AuthFilter",
        urlPatterns = {"/api/auth"},
        description = "Convert request data!"
)
public class AuthFilter implements Filter {
    private String ctxPath;

    @Override
    public void init(FilterConfig filterConfig) {
        ctxPath = filterConfig.getServletContext().getContextPath();
    }

    private String addPath() {
        return ctxPath.concat("/");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String action = httpRequest.getParameter("action");

        // 判断活动参数是否存在
        if (action.isEmpty()) {
            httpResponse.sendRedirect(this.addPath());
            return;
        }

        // 如果不是退出请求
        if (!action.equals("logout")) {
            RequestParams requestParams = new RequestParams(
                    httpRequest.getParameter("username"),
                    httpRequest.getParameter("password")
            );
            request.setAttribute("requestParams", requestParams);
        }

        // 继续执行 Auth 过滤器
        chain.doFilter(request, response);
    }
}
